package com.kehongborui.empmanagesys.controller;

import com.kehongborui.empmanagesys.dao.EmpDao;
import com.kehongborui.empmanagesys.entity.Emp;
import com.kehongborui.empmanagesys.mapper.EmpMapper;
import com.kehongborui.empmanagesys.model.Page;
import com.kehongborui.empmanagesys.model.QueryCondition;
import com.kehongborui.empmanagesys.service.LoginService;
import com.kehongborui.empmanagesys.service.QueryService;
import com.kehongborui.empmanagesys.util.CommonUtil;
import com.kehongborui.empmanagesys.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-07-18
 */
@WebServlet("*.html")
public class ActionServlet extends HttpServlet {
    private static String LOGIN = "login";
    private static String TO_LOGIN = "tologin";
    private static String ADD_EMP = "addEmp";
    private static String ADD = "add";
    private static String LIST_EMP = "listEmp";
    private static String UPDATE_EMP = "updateEmp";
    private static String UPDATE = "update";
    private static String DELETE = "delete";
    private static String QUERY = "query";
    private static String LOGOUT = "logout";

    private LoginService loginService = new LoginService();
    private QueryService queryService = new QueryService();
    private EmpDao empDao = new EmpDao();
    /**
     * 重写父类 service 方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 2. 获取资源路径（uri）
        String uri = req.getRequestURI();
        // 2.1 截取真实的 uri(执行动作)
        String action = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("."));
        // 3. 根据资源路径去做相应的业务处理
        if (action.equals(TO_LOGIN)) {
            String username = req.getParameter("username");
            String password = req.getParameter("password");

            boolean success = loginService.login(username, password);
            if (success) {  // 登录成功的业务逻辑
                // 登录成功后，将用户信息放到session当中去，并重定向到 listemp.html
                req.getSession().setAttribute("LOGIN_USER", username);
                resp.sendRedirect("listEmp.html");
            } else {  // 登录失败过后的业务逻辑
                // 您输入的用户信息不正确
                req.setAttribute("err_msg", "您输入的用户信息不正确");
                req.getRequestDispatcher("WEB-INF/jsp/main/login.jsp").forward(req, resp);
            }
        } else if (action.equals(LOGIN)) {  // 转发到登录页面
            req.getRequestDispatcher("WEB-INF/jsp/main/login.jsp").forward(req, resp);

        } else if (action.equals(LIST_EMP)) { // 根据 listEmp action 转发 listEmp.jsp
            String current = req.getParameter("current");
//            String size = req.getParameter("size");
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setName(req.getParameter("name"));
            queryCondition.setGender(isEmpty(req.getParameter("gender")) ? null : Integer.parseInt(req.getParameter("gender")));
            queryCondition.setSalMin(isEmpty(req.getParameter("salMin")) ? null : Integer.parseInt(req.getParameter("salMin")));
            queryCondition.setAge(isEmpty(req.getParameter("age")) ? null : Integer.parseInt(req.getParameter("age")));
            queryCondition.setSalMax(isEmpty(req.getParameter("salMax")) ? null : Integer.parseInt(req.getParameter("salMax")));
            // 分页对象
            Page page = new Page();

            page.setCurrent(Integer.parseInt(CommonUtil.isEmpty(current) ? "1" : current));

            // 获取session工厂类
            SqlSessionFactory sessionFactory = SqlSessionFactoryUtil.getSqlSessionFactory02();
            // 从工厂类中获取session
            SqlSession session = sessionFactory.openSession();
            // 获取Mapper代理对象
            EmpMapper mapper = session.getMapper(EmpMapper.class);
            List<Emp> empList = mapper.findAll(queryCondition, page);
            Integer amount = mapper.amount(queryCondition);
            page.setAmount(amount);

            req.setAttribute("query", queryCondition);
            // 想req 放临时数据
            req.setAttribute("empList", empList);
            // 设置 page 分页
            req.setAttribute("page", page);
            req.getRequestDispatcher("WEB-INF/jsp/main/listEmp.jsp").forward(req, resp);
        } else if (action.equals(UPDATE_EMP)) {  // 转发到修改员工信息页面
            // 获取url中参数
            String id = req.getParameter("id");
            Emp emp = empDao.findById(Integer.parseInt(id));
            // 转发
            req.setAttribute("emp", emp);
            req.getRequestDispatcher("WEB-INF/jsp/main/update.jsp").forward(req, resp);
        } else if (action.equals(UPDATE)) {
            // 将从前端传来的数据，放到数据库中
            Emp emp = new Emp();
            emp.setId(Integer.parseInt(req.getParameter("id")));
            emp.setName(req.getParameter("name"));
            emp.setIdCardNo(req.getParameter("idCardNo"));
            emp.setGender(Integer.parseInt(req.getParameter("gender")));

            emp.setBirth(string2Timestamp(req.getParameter("birth")));
            emp.setHiredate(string2Timestamp(req.getParameter("hiredate")));
            emp.setLeavedate(string2Timestamp(req.getParameter("leavedate")));
            emp.setStatus(Integer.parseInt(req.getParameter("status")));

            if (empDao.updateById(emp)) {
                resp.sendRedirect("listEmp.html");
            } else {
                // TODO 处理异常
                resp.sendRedirect("error.html");
            }
        } else if (action.equals(DELETE)) {
            if (empDao.deleteById(Integer.parseInt(req.getParameter("id")))) {
                resp.sendRedirect("listEmp.html");
            } else {
                // TODO 处理异常
                resp.sendRedirect("error.html");
            }
        } else if (action.equals(ADD_EMP)) {
            req.getRequestDispatcher("WEB-INF/jsp/main/addEmp.jsp").forward(req, resp);
        } else if (action.equals(ADD)) {
            // 1. 获取数据
            // 2. 封装java bean,交给dao保存
            // 3. 保存成功，重定向listEmp这个页面否则跑错误页面
            // 将从前端传来的数据，放到数据库中
            Emp emp = new Emp();
            emp.setName(req.getParameter("name"));
            emp.setIdCardNo(req.getParameter("idCardNo"));
            emp.setGender(Integer.parseInt(req.getParameter("gender")));

            emp.setBirth(string2Timestamp(req.getParameter("birth")));
            emp.setHiredate(string2Timestamp(req.getParameter("hiredate")));
            emp.setLeavedate(string2Timestamp(req.getParameter("leavedate")));
            emp.setStatus(Integer.parseInt(req.getParameter("status")));

            if (empDao.save(emp)) {
                resp.sendRedirect("listEmp.html");
            } else {
                // TODO 处理异常
                resp.sendRedirect("error.html");
            }
        } else if (action.equals(QUERY)) {  // 查询 String name, String age, String salMin, String salMax, String gender
            List<Emp> empList = queryService.query(req.getParameter("name"),
                    req.getParameter("age"),
                    req.getParameter("salMin"),
                    req.getParameter("salMax"),
                    req.getParameter("gender"));
            // 想req 放临时数据
            req.setAttribute("empList", empList);
            req.setAttribute("name", req.getParameter("name"));
            req.getRequestDispatcher("WEB-INF/jsp/main/listEmp.jsp").forward(req, resp);
        } else if (action.equals(LOGOUT)) {
            // 清除当前客户端对应的session
            req.getSession().invalidate();
            resp.sendRedirect("login.html");
        }
    }

    /**
     * 字符串转日期
     * @param date
     * @return
     */
    public Date string2Date(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date d = null;
        try {
            d = format.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d;
    }

    /**
     * 字符串转日期
     * @param date
     * @return
     */
    public Timestamp string2Timestamp(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Timestamp t = null;
        try {
            t = new Timestamp(format.parse(date).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return t;
    }

    public boolean isEmpty(String value) {
        return value == null || "".equals(value);
    }
}
